package com.leospring.weather.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.itheima.retrofitutils.ItheimaHttp;
import com.itheima.retrofitutils.Request;
import com.itheima.retrofitutils.listener.HttpResponseListener;
import com.leospring.weather.bean.GitFileContent;
import com.leospring.weather.bean.GitUpdateResult;
import com.leospring.weather.cache.GitCache;
import com.leospring.weather.utils.Base64Utils;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Call;
import us.feras.mdv.MarkdownView;

/**
 * Created by Administrator on 2018/11/13.
 */

public class GitEditActivity extends AppCompatActivity {

    private static final int INIT = 1;
    private TextView editFilePath;

    private Button editOrSave,preView;

    private EditText editText;

    private GitFileContent content;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    showEdit(msg.obj);
                    break;
                default:
                    break;
            }
        }

    };

    private void showEdit(Object obj) {
        content = (GitFileContent) obj;
        String s = Base64Utils.setDecrypt(content.getContent());
        editText.setText(s);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ItheimaHttp.init(this, "https://api.github.com/");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.git_edit);
        MarkdownView markdownView = new MarkdownView(this);

        String path = getIntent().getStringExtra("path");
        editFilePath = findViewById(R.id.git_edit_path);
        editOrSave = findViewById(R.id.git_edit);
        editOrSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(editOrSave.getText().equals("Edit")) {
                    editText.setEnabled(true);
                    editText.setFocusable(true);
                    editText.setFocusableInTouchMode(true);
                    editText.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(editText,0);
                    editOrSave.setText("Save");
                } else {
                    System.out.println("Save............");
                    Request request = ItheimaHttp.newPutRequest(path);
                    request.putHeader("Authorization",GitCache.getGitUser().getAuthorization());
                    request.putMediaType(MediaType.parse("application/json"));
                    request.putParams("message","update contents");
                    request.putParams("content",Base64Utils.setEncryption(editText.getText().toString()));
                    request.putParams("sha",content.getSha());
                    ItheimaHttp.send(request, new HttpResponseListener<GitUpdateResult>() {
                        @Override
                        public void onResponse(GitUpdateResult o, Headers headers) {
                            Toast mToast = Toast.makeText(GitEditActivity.this, null, Toast.LENGTH_SHORT);
                            mToast.setText("更新成功.");

                            mToast.show();
//                            Toast.makeText(GitEditActivity.this,"更新成功！",Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable e) {
                            super.onFailure(call, e);
                        }
                    });

                    editText.setEnabled(false);
                    editText.setFocusable(false);
                    editOrSave.setText("Edit");
                }
            }
        });
        preView = findViewById(R.id.git_edit_preview);
        preView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setContentView(markdownView);
                markdownView.loadMarkdown(editText.getText().toString());
            }
        });
        editText = findViewById(R.id.git_edit_content);
        editText.setMovementMethod(ScrollingMovementMethod.getInstance());
//        editText.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (v.getId() == R.id.git_edit_content) {
//                    v.getParent().requestDisallowInterceptTouchEvent(true);//组织父节点消耗滑动事件
//                    switch (event.getAction() & MotionEvent.ACTION_MASK) {
//                        case MotionEvent.ACTION_UP:
//                            v.getParent().requestDisallowInterceptTouchEvent(false);
//                            break;
//                    }
//                }
//                return false;
//            }
//        });

        editFilePath.setText(path);

        init(path);

    }

    private void init(String path) {
        Request request = ItheimaHttp.newGetRequest(path);
        request.putHeader("Authorization",GitCache.getGitUser().getAuthorization());
        ItheimaHttp.send(request, new HttpResponseListener<GitFileContent>() {
//            @Override
//            public void onResponse(GitFileContent bean) {
//                Message message = new Message();
//                message.what = INIT;
//                message.obj = bean;
//                mHandler.sendMessage(message);
//            }

            @Override
            public void onResponse(GitFileContent bean, Headers headers) {
                Message message = new Message();
                message.what = INIT;
                message.obj = bean;
                mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable e) {
            }
        });
    }
}
